package com.nl.lib_core.tool.screenshot;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.view.PixelCopy;
import android.view.View;

import org.jetbrains.annotations.NotNull;

/**
 * 屏幕截图
 */
public class CapturePictureUtils {


    /**
     * View转换成Bitmap
     *
     * @param targetView     targetView
     * @param getCacheResult 转换成功回调接口
     */
    public static void getBitmapFromView(@NotNull Activity activity, View targetView, final CacheResult getCacheResult) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //准备一个bitmap对象，用来将copy出来的区域绘制到此对象中
            final Bitmap bitmap = Bitmap.createBitmap((int) (targetView.getHeight() / 1.4 - 30), targetView.getHeight(), Bitmap.Config.ARGB_8888);
            //获取layout的left-top顶点位置
            final int[] location = new int[2];
            targetView.getLocationInWindow(location);
            //请求转换
            PixelCopy.request(activity.getWindow(),
                    new Rect(0, location[1],
                            0 + (int) (targetView.getHeight() / 1.4), location[1] + targetView.getHeight()),
                    bitmap, copyResult -> {
                        //如果成功
                        if (copyResult == PixelCopy.SUCCESS) {
                            //方法回调
                            getCacheResult.result(bitmap);
                        }
                    }, new Handler(Looper.getMainLooper()));
        } else {
            //开启DrawingCache
            targetView.setDrawingCacheEnabled(true);
            //构建开启DrawingCache
            targetView.buildDrawingCache();
            //获取Bitmap
            Bitmap drawingCache = targetView.getDrawingCache();
            //方法回调
            getCacheResult.result(drawingCache);
            //销毁DrawingCache
            targetView.destroyDrawingCache();
        }
    }


}
